package com.wzy.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wzy.bean.InMessage;
import com.wzy.bean.OutMessage;
import com.wzy.config.WxConfig;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * @Author: wzy
 * @Date: 2022/04/29/11:20
 * @Description:
 */
@RequestMapping("/wx")
@RestController
public class WxController {

    @Autowired
    private WxMpService mpService;

    @Autowired
    private WxMpConfigStorage wxMpConfigStorage;

    // 微信页面填写的token，必须保密
    private static final String TOKEN = "123456";

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     *  对应测试号的配置
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/validate")
    public String validate(String signature,String timestamp,String nonce,String echostr){
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = {timestamp, nonce, TOKEN};
        Arrays.sort(arr);
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder sb = new StringBuilder();
        for (String temp : arr) {
            sb.append(temp);
        }
        // 这里利用了hutool的加密工具类
        String sha1 = SecureUtil.sha1(sb.toString());
        // 3. 加密后的字符串与signature对比，如果相同则该请求来源于微信，原样返回echostr
        if (sha1.equals(signature)){
            return echostr;
        }
        // 接入失败
        return null;
    }

    /**
     * 接受消息处理接口
     * @param inMessage
     * @return
     */
    @PostMapping(value = "validate", produces = "application/xml;charset=UTF-8")
    public Object handleMessage(@RequestBody InMessage inMessage){
        // 创建响应消息实体对象
        OutMessage outMessage = new OutMessage();
        // 把原来的接收方设置为发送方
        outMessage.setFromUserName(inMessage.getToUserName());
        // 把原来的发送方设置为接收方
        outMessage.setToUserName(inMessage.getFromUserName());
        // 设置消息类型
        outMessage.setMsgType(inMessage.getMsgType());
        // 设置消息时间
        outMessage.setCreateTime(System.currentTimeMillis());
        // 根据接收到消息类型，响应对应的消息内容
        if ("text".equals(inMessage.getMsgType())){
            // 文本
            outMessage.setContent(inMessage.getContent());
        }else if ("image".equals(inMessage.getMsgType())){
            // 图片
            outMessage.setMediaId(new String[]{inMessage.getMediaId()});
        }else if ("voice".equals(inMessage.getMsgType())){
            // 语音
            outMessage.setMediaId(new String[]{inMessage.getMediaId()});
        } else if ("video".equals(inMessage.getMsgType())){
            // 视频
            outMessage.setThumbMediaId(inMessage.getThumbMediaId());
            outMessage.setMediaId(new String[]{inMessage.getMediaId()});
        }else if ("event".equals(inMessage.getMsgType())){
            String event = inMessage.getEvent();
            if ("subscribe".equals(event)){
                // 回复
                outMessage.setMsgType("text");
                outMessage.setContent("欢迎关注！");
            }
            if ("unsubscribe".equals(event)){
                // 回复
                outMessage.setMsgType("text");
                outMessage.setContent("很遗憾！！！");
            }
        }
        return outMessage;
    }




    @GetMapping("/getAccessToken")
    public String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxConfig.getAppId() +
                "&secret=" + wxConfig.getSecret();
        // 利用hutool的http工具类请求获取access_token
        String result = HttpUtil.get(url);
        // 将结果解析为json
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 获取access_token
        String accessToken = jsonObject.getStr("access_token");
        if (!StringUtils.isEmpty(accessToken)){
            // 将access_token存入redis
            stringRedisTemplate.opsForValue().set("access_token", accessToken);
        }
        return accessToken;
    }

    @GetMapping("/createMenu")
    public String createMenu(){
        // 从redis中取出access_token
        String accessToken = stringRedisTemplate.opsForValue().get("access_token");
        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
        // 创建菜单的请求体
        // String body = "{\n" +
        //         "     \"button\":[\n" +
        //         "     {\t\n" +
        //         "          \"type\":\"click\",\n" +
        //         "          \"name\":\"位置\",\n" +
        //         "          \"key\":\"button_location\"\n" +
        //         "      }]}";
        String body = "{\n" +
                "  \"button\": [\n" +
                "    {\n" +
                "      \"name\": \"扫码\",\n" +
                "      \"sub_button\": [\n" +
                "        {\n" +
                "          \"type\": \"scancode_waitmsg\",\n" +
                "          \"name\": \"扫码带提示\",\n" +
                "          \"key\": \"rselfmenu_0_0\",\n" +
                "          \"sub_button\": []\n" +
                "        },\n" +
                "        {\n" +
                "          \"type\": \"scancode_push\",\n" +
                "          \"name\": \"扫码推事件\",\n" +
                "          \"key\": \"rselfmenu_0_1\",\n" +
                "          \"sub_button\": []\n" +
                "        }\n" +
                "      ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"name\": \"发图\",\n" +
                "      \"sub_button\": [\n" +
                "        {\n" +
                "          \"type\": \"click\",\n" +
                "          \"name\": \"系统拍照发图\",\n" +
                "          \"key\": \"rselfmenu_1_0\",\n" +
                "          \"sub_button\": []\n" +
                "        },\n" +
                "        {\n" +
                "          \"type\": \"click\",\n" +
                "          \"name\": \"拍照或者相册发图\",\n" +
                "          \"key\": \"rselfmenu_1_1\",\n" +
                "          \"sub_button\": []\n" +
                "        },\n" +
                "        {\n" +
                "          \"type\": \"click\",\n" +
                "          \"name\": \"微信相册发图\",\n" +
                "          \"key\": \"rselfmenu_1_2\",\n" +
                "          \"sub_button\": []\n" +
                "        }\n" +
                "      ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"name\": \"发送位置\",\n" +
                "      \"type\": \"location_select\",\n" +
                "      \"key\": \"button_location\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        return HttpUtil.post(url, body);
    }
    @GetMapping("/deleteMenu")
    public String deleteMenu(){
        // 从redis中取出access_token
        String accessToken = stringRedisTemplate.opsForValue().get("access_token");
        String url = " https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken;
        return HttpUtil.get(url);
    }

    /**
     * 	7mBO05oDOR0Ua8XBZYP5I4rewASKuI6BSDzNGdILj9k
     * @return
     * @throws WxErrorException
     *  根据模板发送消息
     */
    @GetMapping("/send")
    public String sendMessageByTemplate(){
        String body = "{\n" +
                "  \"touser\": \"oY5gD6dAIOfvDbiLKhoJPi33Vrcs\",\n" +
                "  \"template_id\": \"7mBO05oDOR0Ua8XBZYP5I4rewASKuI6BSDzNGdILj9k\",\n" +
                "  \"data\": {\n" +
                "    \"salary\": {\n" +
                "      \"value\": 30000,\n" +
                "      \"color\": \"#173177\"\n" +
                "    },\n" +
                "    \"month\": {\n" +
                "      \"value\": \"8月\",\n" +
                "      \"color\": \"#173177\",\n" +
                "      \"size\": \"18\"\n" +
                "    }\n" +
                "     }\n" +
                "}";
        String accessToken = stringRedisTemplate.opsForValue().get("access_token");
        String url = " https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        return HttpUtil.post(url,body);
    }

    @GetMapping("/test")
    public String testGet() throws WxErrorException {
        System.out.println("***** START *****");
        System.out.println(wxMpConfigStorage.getAccessToken());
        return  this.mpService.getAccessToken();
    }

    @GetMapping("message")
    public String configAccess(String signature,String timestamp,String nonce,String echostr) {
        // 校验签名
        if (mpService.checkSignature(timestamp, nonce, signature)){
            // 校验成功原样返回echostr
            return echostr;
        }
        // 校验失败
        return null;
    }
}
